package com.yichi;

import android.graphics.Color;
import android.os.Bundle;
import android.text.SpannableString;
import android.text.Spanned;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentActivity;
import androidx.lifecycle.Observer;

import com.jeremyliao.liveeventbus.LiveEventBus;
import com.yichi.device_bean.BatteryStore;
import com.yichi.global.EventDef;
import com.yichi.manager.OnHttpResponseListener;
import com.yichi.model.BatteryModel;
import com.yichi.service.DeviceService;
import com.yichi.service.PlatformService;
import com.yichi.util.JsonUtil;
import com.yichi.util.MapUtil;
import com.yichi.util.ProgressBar;
import com.yichi.util.ToastUtil;
import com.yichi.widget.RadiusBackgroundSpan;

import java.io.IOException;
import java.time.temporal.ValueRange;
import java.util.Map;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

import okhttp3.Call;
import okhttp3.Response;

public class QuDianSelectFragment extends Fragment {

    private final static String TAG = "QuDianSelectFragment";
    private TextView tip, tvCountDown;
    private TextView button_back, button_qd, button_cd;

    private BatteryModel batteryModel;
    private String realName;

    ProgressBar progressBar;

    //倒计时
    private ScheduledExecutorService scheduler;
    private int secondsRemaining = 60;  // 总倒计时时间（秒）

    public QuDianSelectFragment(String realName) {
        this.realName = realName;
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fg_qudian_select, container, false);
        findView(view);
        setView();
        progressBar = new ProgressBar(getContext(), R.style.CommProgressDialog);
        //启动倒计时
        scheduler = Executors.newSingleThreadScheduledExecutor();
        startCountdown();
        //
        registerEvent();
        return view;
    }

    private Observer<BatteryModel> observerTake = new Observer<BatteryModel>() {
        @Override
        public void onChanged(BatteryModel batteryModel) {
            button_qd.setVisibility(View.VISIBLE);
            button_cd.setVisibility(View.GONE);
            QuDianSelectFragment.this.batteryModel = batteryModel;
        }
    };

    private Observer<BatteryModel> observerReturun = new Observer<BatteryModel>() {
        @Override
        public void onChanged(BatteryModel batteryModel) {
            button_cd.setVisibility(View.VISIBLE);
            button_qd.setVisibility(View.GONE);
            QuDianSelectFragment.this.batteryModel = batteryModel;
        }
    };

    private void registerEvent() {
        LiveEventBus.get(EventDef.EVENT_USER_FACE_TAKE_OPER, BatteryModel.class).observe(this, observerTake);
        LiveEventBus.get(EventDef.EVENT_USER_FACE_RETURN_OPER, BatteryModel.class).observe(this, observerReturun);
    }

    private void findView(View view) {
        tip = view.findViewById(R.id.qu_dian_tip);
        tvCountDown = view.findViewById(R.id.tvCountDown);
        button_back = view.findViewById(R.id.button_back);
        button_qd = view.findViewById(R.id.button_qd);
        button_cd = view.findViewById(R.id.button_cd);
    }

    private void setView() {
        SpannableString spannableString = new SpannableString(String.format("用户【%s】您好，\n 请在左侧选择存取的电池格口", this.realName));
//        RadiusBackgroundSpan backgroundColorSpan = new RadiusBackgroundSpan(Color.parseColor("#FFFFE60F"), 0, Color.BLACK, 28, 0, "左侧");
//        spannableString.setSpan(backgroundColorSpan, 14, 15, Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
        tip.setText(spannableString);

        button_qd.setVisibility(View.GONE);
        button_cd.setVisibility(View.GONE);

        //返回
        button_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                goHome();
            }
        });

        //存
        button_cd.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                handleCun(batteryModel);
            }
        });

        //取
        button_qd.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                handleQv(batteryModel);
            }
        });
    }

    //执行存
    private void handleCun(BatteryModel batteryModel) {
        BatteryStore batteryStore = DeviceService.inst.getBatteryStoreByStoreNo(batteryModel.getStoreNo());
        if (batteryStore.getHasBattery() || !batteryStore.getLockStatus().equals(0)) {
            ToastUtil.show(getContext(), String.format("%s号存电仓，暂不可用", batteryModel.getPosition()));
            return;
        }

        //调用api创建取的订单
        progressBar.show();
        try {
            PlatformService.updateCabinetStillBattery(batteryStore, new OnHttpResponseListener() {
                @Override
                public void success(Call call, Response response) throws IOException {
                    progressBar.dismiss();
                    String s = response.body().string();
                    Map<String, Object> map;
                    try {
                        map = JsonUtil.parseMap(s);
                    } catch (Exception e) {
                        FragmentActivity fragmentActivity = requireActivity();
                        if (isAdded()) {
                            requireActivity().runOnUiThread(()->{
                                ToastUtil.show(getContext(), "格式错误：" + s);
                            });
                        }
                        return;
                    }
                    Integer code = MapUtil.getInteger(map, "code");
                    String msg = MapUtil.getString(map, "msg");
                    if (code != 200) {
                        requireActivity().runOnUiThread(()->{
                            ToastUtil.show(getContext(), "平台错误：" + msg);
                        });
                        return;
                    }
                    Map dataMap = MapUtil.getMap(map, "data");
                    if (dataMap == null) {
                        requireActivity().runOnUiThread(()->{
                            ToastUtil.show(getContext(), "平台错误：未获取到订单数据");
                        });
                        return;
                    }
                    Log.i(TAG, JsonUtil.toJSONString(dataMap));
                    LiveEventBus.get(EventDef.EVENT_USER_FACE_POER_OK, String.class).post(null);
                    goNextCD(batteryStore, dataMap);
                    //{"code":200,"msg":"请电池成功","data":{"id":258,"no":null,"tradeOrderNo":"20250323181737185230A5","type":0,"terminal":null,"userId":230,"userIp":"192.168.1.20","userRemark":null,"remark":null,"payOrderId":null,"payStatus":0,"payTime":null,"payChannelCode":null,"finishTime":null,"cancelTime":null,"totalAmount":"0.00","discountAmount":"0.00","adjustAmount":"0.00","meetAmount":"0.00","payAmount":"0.00","refundAmount":"0.00","couponId":null,"couponJson":null,"couponVo":{"id":null,"areaId":null,"areaName":null,"couponName":null,"couponUrl":null,"couponSubtitle":null,"couponDescribe":null,"couponSynopsis":null,"payPrice":null,"subtractPrice":null,"discount":null,"nums":null,"useNums":null,"startTime":null,"endTime":null,"couponType":null,"sorted":null,"state":null,"remark":null,"expiresTime":null,"isUsed":null,"createTime":null,"updateTime":null,"createByName":null,"updateByName":null,"createBy":null,"updateBy":null},"couponPrice":"0.00","startTime":"2025-03-23 18:17:37","endTime":null,"orderState":31,"paymentMethod":null,"areaId":5,"areaName":"太原迎泽","uniqueOrder":null,"cabinetId":5,"takeCabinetVo":{"id":5,"stationId":4,"cabinetTheme":"cloud_to_bat_YCHDJSNJ000001","stationName":null,"cabinetName":"南中环电柜1","cabinetNum":"YCHDJSNJ000001","batteryNum":10000,"batteryActualNum":null,"supplierId":3,"supplierName":null,"cabinetParameters":"1","cabinetParametersState":"1","state":1,"remark":null,"agentId":110,"electStationVo":null,"batteryCanUsedNum":null,"serveAddr":"1","batteryList":null,"batteryArray":null,"createTime":"2025-01-04 21:24:56","updateTime":"2025-01-10 22:01:06","createByName":null,"updateByName":null,"createBy":1,"updateBy":1},"stationId":4,"takeStationVo":{"id":4,"areaId":5,"areaName":null,"fenceId":11,"fenceName":null,"stationName":"南中环PM换电站","stationNum":"PMTY001","stationId":null,"address":"数码西路","lng":"112.708614","lat":"37.713475","startTime":"00:52:59","endTime":"23:53:59","startWeek":"1","endWeek":"7","province":"山西省","city":"太原市","county":"市辖区","cityCode":"140100000000","countyCode":"140101000000","provinceCode":"140000000000","state":1,"remark":null,"headImg":"https://sxzkycoss.oss-cn-beijing.aliyuncs.com/202501082119284983aa13-bb15-461a-b53d-1dd7ae063816.png","distance":null,"cabinetList":null,"cabinetName":null,"cabinetId":null,"cabinetNum":null,"batteryNum":null,"batteryActualNum":null,"batteryCanUsedNum":null,"createTime":"2025-01-03 23:56:41","updateTime":"2025-01-08 21:19:31","createByName":null,"updateByName":null,"createBy":1,"updateBy":1},"batteryId":null,"takeBatteryVo":{"id":null,"areaId":null,"areaName":null,"fenceId":null,"fenceName":null,"electModel":null,"batteryNum":null,"batteryBmsNum":null,"supplierId":null,"supplierName":null,"cycleTimes":null,"remainingCapacity":null,"voltage":null,"batteryType":null,"cabinetParameters":null,"cabinetParametersState":null,"state":null,"remark":null,"createTime":null,"updateTime":null,"createByName":null,"updateByName":null,"createBy":null,"updateBy":null},"stillBatteryVo":{"id":null,"areaId":null,"areaName":null,"fenceId":null,"fenceName":null,"electModel":null,"batteryNum":null,"batteryBmsNum":null,"supplierId":null,"supplierName":null,"cycleTimes":null,"remainingCapacity":null,"voltage":null,"batteryType":null,"cabinetParameters":null,"cabinetParametersState":null,"state":null,"remark":null,"createTime":null,"updateTime":null,"createByName":null,"updateByName":null,"createBy":null,"updateBy":null},"stillCabinetId":null,"stillCabinetVo":{"id":null,"stationId":null,"cabinetTheme":null,"stationName":null,"cabinetName":null,"cabinetNum":null,"batteryNum":null,"batteryActualNum":null,"supplierId":null,"supplierName":null,"cabinetParameters":null,"cabinetParametersState":null,"state":null,"remark":null,"agentId":null,"electStationVo":null,"batteryCanUsedNum":null,"serveAddr":null,"batteryList":null,"batteryArray":null,"createTime":null,"updateTime":null,"createByName":null,"updateByName":null,"createBy":null,"updateBy":null},"stillStationId":null,"stillStationVo":{"id":null,"areaId":null,"areaName":null,"fenceId":null,"fenceName":null,"stationName":null,"stationNum":null,"stationId":null,"address":null,"lng":null,"lat":null,"startTime":null,"endTime":null,"startWeek":null,"endWeek":null,"province":null,"city":null,"county":null,"cityCode":null,"countyCode":null,"provinceCode":null,"state":null,"remark":null,"headImg":null,"distance":null,"cabinetList":null,"cabinetName":null,"cabinetId":null,"cabinetNum":null,"batteryNum":null,"batteryActualNum":null,"batteryCanUsedNum":null,"createTime":null,"updateTime":null,"createByName":null,"updateByName":null,"createBy":null,"updateBy":null},"createTime":"2025-03-23 18:17:37","packageOrderId":null,"packageOrderJson":null,"refundNo":null,"takeBatteryJson":null,"takeStationJson":null,"takeCabinetJson":null,"stillBatteryJson":null,"stillStationJson":null,"stillCabinetJson":null,"isTakeBattery":0,"takeBatteryDate":null,"takeCloseDoor":0,"takeCloseDoorDate":null,"isReturnBattery":0,"returnBatteryDate":null,"returnCloseDoor":0,"closeDoorDate":null}}
                }

                @Override
                public void failed(Call call, IOException e) {
                    progressBar.dismiss();
                    Log.e(TAG, e.getMessage(), e);
                    requireActivity().runOnUiThread(()->{
                        ToastUtil.show(getContext(), "内部错误：" + e.getMessage());
                    });
                }
            });
        } catch (Exception e) {
            progressBar.dismiss();
            Log.e(TAG, e.getMessage(), e);
            ToastUtil.show(getContext(), "内部错误：" + e.getMessage());
        }
    }

    //执行取
    private void handleQv(BatteryModel batteryModel) {
        BatteryStore batteryStore = DeviceService.inst.getBatteryStoreByStoreNo(batteryModel.getStoreNo());
        if (!batteryStore.getHasBattery() || !batteryStore.getLockStatus().equals(0)) {
            ToastUtil.show(getContext(), String.format("%s号取电仓，暂不可用", batteryModel.getPosition()));
            return;
        }

        //调用api创建取的订单
        progressBar.show();
        try {
            PlatformService.addCabinetTakeBattery(batteryStore, new OnHttpResponseListener() {
                @Override
                public void success(Call call, Response response) throws IOException {
                    progressBar.dismiss();
                    String s = response.body().string();
                    Map<String, Object> map;
                    try {
                        map = JsonUtil.parseMap(s);
                    } catch (Exception e) {
                        requireActivity().runOnUiThread(()->{
                            ToastUtil.show(getContext(), "格式错误：" + s);
                        });
                        return;
                    }
                    Integer code = MapUtil.getInteger(map, "code");
                    String msg = MapUtil.getString(map, "msg");
                    if (code != 200) {
                        requireActivity().runOnUiThread(()->{
                            ToastUtil.show(getContext(), "平台错误：" + msg);
                        });
                        return;
                    }
                    Map dataMap = MapUtil.getMap(map, "data");
                    if (dataMap == null) {
                        requireActivity().runOnUiThread(()->{
                            ToastUtil.show(getContext(), "平台错误：未获取到订单数据");
                        });
                        return;
                    }
                    Log.i(TAG, JsonUtil.toJSONString(dataMap));
                    LiveEventBus.get(EventDef.EVENT_USER_FACE_POER_OK, String.class).post(null);
                    goNextQD(batteryStore, dataMap);
                    //{"msg":"请电池成功","code":200,"data":{"discountAmount":"0.00","stillBatteryVo":{},"type":0,"orderState":31,"couponVo":{},"payAmount":"0.00","areaName":"太原迎泽","takeCloseDoor":0,"id":253,"stationId":4,"returnCloseDoor":0,"isReturnBattery":0,"isTakeBattery":0,"tradeOrderNo":"20250323175529088230A5","adjustAmount":"0.00","totalAmount":"0.00","cabinetId":5,"startTime":"2025-03-23 17:55:29","refundAmount":"0.00","takeBatteryVo":{},"takeStationVo":{"city":"太原市","cityCode":"140100000000","county":"市辖区","stationNum":"PMTY001","province":"山西省","updateBy":1,"stationName":"南中环PM换电站","startTime":"00:52:59","id":4,"endWeek":"7","state":1,"lat":"37.713475","startWeek":"1","address":"数码西路","lng":"112.708614","headImg":"https://sxzkycoss.oss-cn-beijing.aliyuncs.com/202501082119284983aa13-bb15-461a-b53d-1dd7ae063816.png","provinceCode":"140000000000","updateTime":"2025-01-08 21:19:31","countyCode":"140101000000","createBy":1,"areaId":5,"createTime":"2025-01-03 23:56:41","endTime":"23:53:59","fenceId":11},"userId":230,"takeCabinetVo":{"agentId":110,"supplierId":3,"serveAddr":"1","batteryNum":10000,"updateBy":1,"id":5,"state":1,"stationId":4,"cabinetParametersState":"1","cabinetName":"南中环电柜1","updateTime":"2025-01-10 22:01:06","createBy":1,"cabinetTheme":"cloud_to_bat_YCHDJSNJ000001","createTime":"2025-01-04 21:24:56","cabinetParameters":"1","cabinetNum":"YCHDJSNJ000001"},"meetAmount":"0.00","stillStationVo":{},"areaId":5,"stillCabinetVo":{},"createTime":"2025-03-23 17:55:29","userIp":"192.168.1.20","couponPrice":"0.00","payStatus":0}}
                }

                @Override
                public void failed(Call call, IOException e) {
                    progressBar.dismiss();
                    Log.e(TAG, e.getMessage(), e);
                    requireActivity().runOnUiThread(()->{
                        ToastUtil.show(getContext(), "内部错误：" + e.getMessage());
                    });
                }
            });
        } catch (Exception e) {
            progressBar.dismiss();
            Log.e(TAG, e.getMessage(), e);
            ToastUtil.show(getContext(), "内部错误：" + e.getMessage());
        }
    }

    //跳到取电页面
    private void goNextQD(BatteryStore batteryStore, Map<String, Object> map) {
        String str1 = String.format("用户【%s】正在取电，请按照提示操作", DeviceService.inst.getDeviceOperInfo() == null ? "" : DeviceService.inst.getDeviceOperInfo().getUserName());
        String str2 = String.format("正在开门请稍等\n请留意仓门");
        Fragment faceOperTipFragment = new FaceOperTipFragment(str1, str2, batteryStore, map, 1);
        getParentFragmentManager().beginTransaction().replace(R.id.login_fragment_container, faceOperTipFragment).commit();
    }

    //跳到存电页面
    private void goNextCD(BatteryStore batteryStore, Map<String, Object> map) {
        String str1 = String.format("用户【%s】正在存电，请按照提示操作", DeviceService.inst.getDeviceOperInfo() == null ? "" : DeviceService.inst.getDeviceOperInfo().getUserName());
        String str2 = String.format("正在开门请稍等\n请留意仓门");
        Fragment faceOperTipFragment = new FaceOperTipFragment(str1, str2, batteryStore, map, 2);
        getParentFragmentManager().beginTransaction().replace(R.id.login_fragment_container, faceOperTipFragment).commit();
    }

    private void goHome() {
        progressBar.dismiss();
        MainActivity mainActivity = (MainActivity) requireActivity();
        mainActivity.goHome();
    }

    private void startCountdown() {
        // 每秒钟执行一次任务
        scheduler.scheduleAtFixedRate(new Runnable() {
            @Override
            public void run() {
                // 更新UI线程
                requireActivity().runOnUiThread(() -> {
                    if (secondsRemaining > 0) {
                        secondsRemaining--;
                        // 计算分钟和秒数
                        int minutes = secondsRemaining / 60;
                        int seconds = secondsRemaining % 60;
                        // 格式化时间为 "00:59"
                        String timeLeft = String.format("%02d:%02d", minutes, seconds);
                        tvCountDown.setText(timeLeft);
                    } else {
                        // 倒计时结束，显示提示
                        scheduler.shutdown();
                        goHome();
                    }
                });
            }
        }, 0, 1, TimeUnit.SECONDS); // 延迟0秒开始，每秒执行一次
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        if (scheduler != null && !scheduler.isShutdown()) {
            scheduler.shutdown();  // 停止定时任务
        }
        LiveEventBus.get(EventDef.EVENT_USER_FACE_TAKE_OPER, BatteryModel.class).removeObserver(observerTake);
        LiveEventBus.get(EventDef.EVENT_USER_FACE_RETURN_OPER, BatteryModel.class).removeObserver(observerReturun);
    }
}
